#! /usr/bin/env python
from Tkinter import *
from math import *
import sys
import os, thread, datetime, string
import PIL
from PIL import Image, ImageTk
import os
import tkFileDialog
import tkMessageBox


files_to_process = []

filestr = tkFileDialog.askopenfilenames(title='Choose a file', filetypes = [('a2p files', '.a2p')])
filestrtemplist = filestr.split(' {')

for each in filestrtemplist:
    each = each.strip('{')
    each = each.strip('}')
    #splittemp = each.rsplit('/', 1)
    #filename = splittemp[1]
    files_to_process.append(each)

print files_to_process
    
for a2pfile in files_to_process:
    #print a2pfile
    
    imagefile = a2pfile.replace('.a2p','.jpg')
    image = Image.open(imagefile)




    
    #photo = ImageTk.PhotoImage(image)
    #can.create_image(320, 240, image=photo)
    #can.image=photo


def process_blot():
    print lb_mainlist.curselection()
    time_to_analyze = en_seconds_to_analyze.get()

    
    try: item = lb_mainlist.get(lb_mainlist.curselection())

    except TclError:
        item = lb_mainlist.get(0)
        lb_mainlist.selection_set(0)

    refresh_canvas()    #CLEAR CANVAS AND REDRAW IMAGE

    #get roi
    f = open(item[1], 'r')
    #load file, settings, xy points
    infoline = f.readline()
    infolist = infoline.split(',')
    infolist[6] = infolist[6].strip('(')
    infolist[9] = infolist[9].strip(')\n')

    print "INFOLIST", infolist
    #save trial name to file
    trialname = infolist[0].split('/')
    run_filename = trialname.pop()

    #get FPS, calculate frames to analyze
    frames_to_analyze = int(time_to_analyze) * int(round(float(infolist[2])))
    print "FRAMES TO ANALYZE: ", frames_to_analyze, "  ",  int(round(float(infolist[2])))

    #get ROI from info list
    #roi_apparatus = eval(infolist[6])
    xypoints = f.readlines() #create xy point coords to analyze
    f.close()


    first_run = True
    lastx = 0
    lasty = 0
    distancetraveled = 0

    #print rectx, recty, rectx2, recty2
    print infolist[6]
    #convert to int
    rectx = int(infolist[6]) - 7
    recty = int(infolist[7]) - 1
    rectx2 = int(infolist[8]) + 3
    recty2 = int(infolist[9]) + 3

    #rectx2 = rectx2 - rectx #convert to rectangle
    #recty2 = recty2 - recty

    print rectx, recty, rectx2, recty2
    #can.create_rectangle(rectx,recty,rectx2,recty2, outline='red')

    #calculate center
    xcenter = (rectx + rectx2)/2
    ycenter = (recty + recty2)/2

    can.create_oval(xcenter, ycenter, xcenter+3, ycenter+3, fill="yellow")

    if checkbox_dispname.get() == 1:
        #display filename
        can.create_text(320,10, text=run_filename, fill="green")

    if checkbox_boxsize.get() == 1: #if display box is checked
        print "Box Size is checked"
        boxsize = en_boxsize.get()
        boxpixsize = float(boxsize) * 3.4
        topleftx = xcenter - boxpixsize *.5
        toplefty = ycenter - boxpixsize *.5
        botrightx = xcenter + boxpixsize *.5
        botrighty = ycenter + boxpixsize *.5

        can.create_rectangle(topleftx, toplefty, botrightx, botrighty, outline='blue')

    if checkbox_blot.get() == 1:
        print "Blot is selected"
        blotsize = en_blot.get()
        for each in xypoints:
            frame_xypoints = []

            frame_xypoints_unformated = each.split(',')
            for item in frame_xypoints_unformated:
                frame_xypoints.append(int(item.strip("\n")))

            print "FRAME XY POINTS", frame_xypoints
            if frame_xypoints[0] > frames_to_analyze:
                break #end analysis

            if first_run == True:
                print "FIRST RUN"
                first_run = False # First point recieved
                lastx = frame_xypoints[1] + rectx
                lasty = frame_xypoints[2] + recty

            else:
                thisx = frame_xypoints[1] + rectx
                thisy = frame_xypoints[2] + recty
                xpoints = abs(thisx - lastx)
                ypoints = abs(thisy - lasty)

                thisdistance = sqrt(pow(xpoints, 2) + pow(ypoints, 2))
                print "THIS DISTANCE: ", thisdistance

                if thisdistance > 30 or thisdistance < 5:
                    thisx = lastx #do nothing
                    thisy = lasty
                    print "Doing nothing"
                else:
                    print "ELSE FIRED!!!!"
                    distancetraveled += thisdistance
                    print "DISTANCE SO FAR: ", distancetraveled
                    lastx = thisx
                    lasty = thisy
                    can.create_oval(thisx, thisy, thisx+int(blotsize), thisy+int(blotsize), fill="red")

    if checkbox_trace.get() == 1:
        pass

    if checkbox_heat.get() == 1:
        pass
    
